package com.carcontrol.rotate;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.carcontrol.rotate.base.BaseActivity;
import com.carcontrol.rotate.util.IntentUtils;
import com.carcontrol.rotate.util.ToastUtil;
import com.monkey.miclockview.MiClockView;

import java.lang.reflect.Method;
import java.util.UUID;

import static android.text.TextUtils.isEmpty;

//登录
public class LoginActivity extends BaseActivity {

    private FrameLayout v;
    private Activity activity;

    private long loopTime = 60 * 1000;  //时间显示间隔   默认1分钟
    private int cn = 10;     //屏保显示间隔   默认10分钟

    Handler handler = new Handler();

    private MiClockView miClockView;

    Object[] allParam = new Object[]{
            new Object[]{"iv", new Rect(0 * width / 1280, 0 * height / 480, 1280 * width / 1280, 480 * height / 480), R.mipmap.bg, false, new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05}},
//            new Object[]{"iv", new Rect(0*width/width0, 0*height/height0, 246*width/width0, 477*height/height0), R.mipmap.bg_left, false, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
//            new Object[]{"iv", new Rect(475*width/width0, 85*height/height0, 483*width/width0, 30*height/height0), R.mipmap.bg_top, false, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},


            new Object[]{"et", new Rect(550 * width / 1280, 250 * height / 480, 0, 0), "", 16, Color.BLACK, true, new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05}, R.drawable.btn_bcg},      //界面按钮数选择

            new Object[]{"tv", new Rect(550 * width / 1280, 200 * height / 480, 0, 0), "ID:", 14, Color.WHITE, true, new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05}, R.drawable.btn_bcg},

            new Object[]{"tv", new Rect(550 * width / 1280, 350 * height / 480, 0, 0), "登录", 16, Color.BLACK, true, new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05}, R.drawable.btn_bcg},


            new Object[]{"mcv", new Rect(0 * width / 1280, 0 * height / 480, 1280 * width / 1280, 480 * height / 480), "小米时钟", 19, Color.BLACK, R.mipmap.clock_bg, R.mipmap.needle_second, R.mipmap.needle_minute, R.mipmap.needle_hour, R.mipmap.open},   //界面背景，时钟背景，秒针，分针，时针，圆心

            new Object[]{"iv", new Rect(1220 * width / 1280, 10 * height / 480, 46 * width / 1280, 34 * height / 480), R.mipmap.back_image, true, new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05}},

    };


    private EditText et;//密码输入框

    private String serialNumber;//设备ID

    private String pwd = "";//密码

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        v = new FrameLayout(this);
        setContentView(v);

        context = this;
        activity = this;

        Log.e("sa===onCreate", width + "===" + height + "===" + density);

        initView();

//        loop();
    }


    /*
     * 获取设备ID并根据ID生成登录密码
     * deviceID的组成为：渠道标志+识别符来源标志+hash后的终端识别符
     *
     * 渠道标志为：
     * 1，andriod（a）
     *
     * 识别符来源标志：
     * 1， wifi mac地址（wifi）；
     * 2， IMEI（imei）；
     * 3， 序列号（sn）；
     * 4， id：随机码。若前面的都取不到时，则随机生成一个随机码，需要缓存。
     *
     * @param context
     * @return
     */
    public String getDeviceId() {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
//        deviceId.append("a");
        try {
            //wifi mac地址
//            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//            WifiInfo info = wifi.getConnectionInfo();
//            String wifiMac = info.getMacAddress();
//            if (!isEmpty(wifiMac)) {
//                deviceId.append("wifi");
//                deviceId.append(wifiMac);
//                Log.e("getDeviceId1 : ", deviceId.toString());
//                return deviceId.toString();
//            }else{
//                Log.e("getDeviceId1 : ", wifiMac);
//            }
            //IMEI（imei）
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return "";
            }

            String imei = tm.getDeviceId();
            if (!isEmpty(imei)) {
//                deviceId.append("imei");
                pwd = toPwd(imei);
                deviceId.append(imei);
                Log.e("getDeviceId2 : ", deviceId.toString());
                return deviceId.toString();
            }

            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if(!isEmpty(sn)){
//                deviceId.append("sn");
                pwd = toPwd(sn);
                deviceId.append(sn);
                Log.e("getDeviceId3 : ", deviceId.toString());
                return deviceId.toString();
            }

            //如果上面都没有， 则生成一个id：随机码
//            String uuid = getUUID(context);
            String uuid = UUID.randomUUID().toString();
            if(!isEmpty(uuid)){
//                deviceId.append("id");
                pwd = toPwd(uuid);
                deviceId.append(uuid);
                Log.e("getDeviceId4 : ", deviceId.toString());
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();

            Log.e("getDeviceIde : ", e+"===");

            deviceId.append("id").append(UUID.randomUUID().toString());
        }
        Log.e("getDeviceId# : ", deviceId.toString());
        return deviceId.toString();
    }

    //根据ID生成密码：用ID的后8位，每位如果是数字*2+1，如果是字母转为0
    String toPwd(String s){
        String s1 = s.substring(s.length()-8, s.length());

        String pwd = "";
        for (int i = 0; i < s1.length(); i++) {
            char c = s1.charAt(i);

            int num = 0;
            if(Character.isDigit(c)){
                num = (Integer.parseInt(String.valueOf(c))*2+1)%10;

                Log.e("toPwd===1", num+"===");
            }else if(Character.isLowerCase(c) || Character.isUpperCase(c)){
                num = 0;


                Log.e("toPwd===2", num+"===");
            }

            pwd+=num;

        }

        Log.e("toPwd===3", pwd+"===");

        return pwd;
    }

    public static String getDeviceSN() {

        String serial = null;

        try {

            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
        } catch (Exception e) {

            e.printStackTrace();

        }

        return serial;

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView(){

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkPermission = this.checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE)) {
                    requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 100);
                } else {

                    requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 100);
                }
                return;
            }
        }
        // <!-- 写入扩展存储，向扩展卡写入数据，用于写入离线定位数据 -->
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkPermission = this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                } else {

                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                }
                return;
            }
        }

        serialNumber = getDeviceId();   //获取设备ID并根据ID生成登录密码


        for (int i=0; i<allParam.length; i++){
            Object[] obj = (Object[])allParam[i];
            Rect rect = (Rect)obj[1];
            String type = (String)obj[0];

            if("tv".equals(type)){
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                String name = (String)obj[2];
                int textSize = (int)obj[3];
                int textColor = (int)obj[4];
                int textBcg = (int)obj[7];
                TextView tv = new TextView(context);
                tv.setText(name);
                tv.setTextSize(textSize);
                tv.setTextColor(textColor);
                if(!name.contains("ID:")){
                    tv.setBackgroundResource(textBcg);
                    tv.setPadding(20*width/width0, 10*height/height0, 20*width/width0, 10*height/height0);
                }else{
                    tv.setText("ID:"+serialNumber);
                }

                v.addView(tv, params);


                boolean isCanClick = (boolean)obj[5];

                if(isCanClick){
                    tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            String name = (String)obj[2];
                            int textBcg = (int)obj[7];

                            Log.e("la===tv", name+"==="+textBcg+"==="+type+"==="+pwd);

//                            if(textBcg==R.mipmap.btn_bcg){
//                                tv.setBackgroundResource(R.mipmap.btn_bcg2);
//                                obj[7] = R.mipmap.btn_bcg2;
//                            }else if(textBcg==R.mipmap.btn_bcg2){
//                                tv.setBackgroundResource(R.mipmap.btn_bcg);
//                                obj[7] = R.mipmap.btn_bcg;
//                            }

                            if("登录".equals(name)){

                                if(pwd.equals(et.getText().toString())){    //判断密码是否正确
                                    ToastUtil.showMessageApp(context, "登录成功！");

                                    IntentUtils.startActivity(activity, SettingActivity.class); //跳转设置界面
                                    finish();
                                }else{
                                    ToastUtil.showMessageApp(context, "密码错误！");
                                }

                            }

                        }
                    });
                }

            }else if("et".equals(type)){    //EditText 加载输入框
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                String name = (String)obj[2];
                int textSize = (int)obj[3];
                int textColor = (int)obj[4];
                int textBcg = (int)obj[7];

                et = new EditText(context);
                et.setText(name);
                et.setTextSize(textSize);
                et.setTextColor(textColor);
                et.setHint("请输入密码");
                et.setHintTextColor(Color.GRAY);
                et.setBackgroundResource(textBcg);
                et.setPadding(10*width/width0, 0*height/height0, 10*width/width0, 0*height/height0);
                v.addView(et, params);


                boolean isCanClick = (boolean)obj[5];
            }else if("iv".equals(type)){
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                int imgSrc = (int)obj[2];
                ImageView iv = new ImageView(context);
                iv.setImageResource(imgSrc);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                v.addView(iv, params);

                boolean isCanClick = (boolean)obj[3];

                if(isCanClick){

                    Log.e("sa===can", imgSrc+"==="+isCanClick);

                    iv.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            int imgId = (int)obj[2];
                            byte[] bytes = (byte[])obj[4];

                            Log.e("sa===iv", imgId+"==="+bytes.length+"==="+bytes);

                            if(imgId==R.mipmap.back_image){
                                IntentUtils.startActivity(activity, MainActivity.class);
                                finishMine();
                            }else if(imgId==R.mipmap.light){
                                iv.setImageResource(R.mipmap.light_0);
                                obj[2] = R.mipmap.light_0;
                            }else if(imgId==R.mipmap.light_0){
                                iv.setImageResource(R.mipmap.light);
                                obj[2] = R.mipmap.light;
                            }else if(imgId==R.mipmap.light_fw){
                                iv.setImageResource(R.mipmap.light_fw_0);
                                obj[2] = R.mipmap.light_fw_0;
                            }else if(imgId==R.mipmap.light_fw_0){
                                iv.setImageResource(R.mipmap.light_fw);
                                obj[2] = R.mipmap.light_fw;
                            }

//                            write(bytes);   //TODO
//                            boolean isSendy = uartJnit.getInstance().sendCmds(cmd); //TODO

                        }
                    });
                }

            }else if("mcv".equals(type)){
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);


                String name = (String)obj[2];
                int textSize = (int)obj[3];
                int textColor = (int)obj[4];

                miClockView = new MiClockView(context, (int)obj[5], (int)obj[6], (int)obj[7], (int)obj[8], (int)obj[9]);
                miClockView.setBackgroundColor(textColor);

                v.addView(miClockView, params);

                miClockView.setVisibility(View.GONE);

                miClockView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        Log.e("mcv===onTouch", "===");

                        miClockView.setVisibility(View.GONE);
                        return false;
                    }
                });

            }
        }
    }



    private void loop(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                long n=0;

                while (true){

                    m_myHandler.sendEmptyMessage(1);

                    try {
                        Thread.sleep(loopTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    n++;

                    if(n%cn==0){
                        m_myHandler.sendEmptyMessage(2);
                    }

                }

            }
        }).start();
    }


    //系统返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        Log.e("onKeyDown===", "==="+keyCode);

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            IntentUtils.startActivity(activity, MainActivity.class);
            finishMine();

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent idata) {

        Log.e("sa===onActivityResult", requestCode+"==="+resultCode);

        switch (requestCode) {
            case 1:
                break;
        }

        super.onActivityResult(requestCode, resultCode, idata);
    }

    //获取手机系统各种权限
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initView();
                } else {
                    CustomDialog.Builder customBuilder = new CustomDialog.Builder(this);
                    customBuilder.setTitle("温馨提示").setMessage("您需要在设置里打开存储空间权限！")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                    finishMine();
                                }
                            }).setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            Intent localIntent = new Intent();
                            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                            startActivity(localIntent);
                            finishMine();
                        }
                    });
                    customBuilder.create().show();
                }
                return;
            case 100:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    initView();
                } else {
//					showDialog();

                    CustomDialog.Builder customBuilder = new CustomDialog.Builder(this);
                    customBuilder.setTitle("温馨提示").setMessage("您需要在设置里允许设备信息权限！")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                    finishMine();
                                }
                            }).setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            Intent localIntent = new Intent();
                            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                            startActivity(localIntent);
                            finishMine();
                        }
                    });
                    customBuilder.create().show();

                }
                return;


            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
